package com.feihong.yw189.activity.shouye;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.MyActivityManager;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.denglu.DengLuActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.dialog.NoticeDialog;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.fragment.shouye.DingDanLieBiaoFragment;
import com.feihong.yw189.fragment.shouye.GeRenZhongXinFragment;
import com.feihong.yw189.fragment.shouye.ShouYeFragment;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.http.RefreshToken;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.localdb.LoginInfoHandler;
import com.feihong.yw189.message.FroceLogOutMessage;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.DBLoginInfoObj;
import com.feihong.yw189.model.notice.NoticeInfo;
import com.feihong.yw189.utils.Location.LocationTools;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

import ezy.boost.update.UpdateManager;

/***
 * 首页 ----应用入口
 *
 */
public class MainActivity extends BaseActivity implements OnTabSelectListener {

    private static final String[] HOME_TABS = {"首页", "订单", "我的"};
    private static final int[] HOME_SelectedICONS = {
            R.mipmap.ic_home, R.mipmap.ic_chooseshouye,
            R.mipmap.my};
    private static final int[] HOME_UNSelectedICONS = {
            R.mipmap.ic_onhome, R.mipmap.iv_shouye,
            R.mipmap.myto};
    public ArrayList<CustomTabEntity> mTabEntities;
    private CommonTabLayout mTabLayout;
    private BaseFragment[] fragments = new BaseFragment[3];
    private BaseFragment currentFragment = null;
    private LocationTools locationTools;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTabLayout = findViewById(R.id.home_tl);
        LoginInfoHandler mHandler = LoginInfoHandler.create(this);
        List<DBLoginInfoObj> infoObjs = mHandler.getLoginInfoObj();
        App.getApp().setUserAccount(infoObjs.get(0).getUserName(), infoObjs.get(0).getPassWord());
        isShowForceExitDialog = new AtomicBoolean(true);
        EventBus.getDefault().register(this);

        initView();
        checkUpdate();
        noticeDialog = new NoticeDialog(this);
        queryMsgInfo();
    }

    NoticeDialog noticeDialog;

    private void queryMsgInfo() {
        App.getApp().getHttpTools().getNoticeMsgInfo(new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    NoticeInfo noticeInfo = JSON.parseObject(result, NoticeInfo.class);
                    if (noticeInfo == null) {
                        return;
                    }
                    int status = noticeInfo.getStatus();
                    if (status == 1 && noticeInfo.getData() != null) {
                        noticeDialog.setContent(noticeInfo.getData());
                        noticeDialog.showDialog();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void setTheme() {

    }

    public String sHA1() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1) {
                    hexString.append("0");
                }
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void checkUpdate() {
        //设置默认更新接口地址与渠道
        UpdateManager.setUrl(HttpTools.UPDATE_APP, "Android");
        //设置不是WIFI也可以检测更新版本 ，默认的是只WIFI情况下检测新版本
        UpdateManager.setWifiOnly(false);
        // 进入应用时查询更新
        UpdateManager.check(this);
    }

    public void initView() {
        mTabEntities = new ArrayList<>();
        for (int i = 0; i < HOME_TABS.length; i++) {
            mTabEntities.add(new TabEntity(HOME_TABS[i], HOME_SelectedICONS[i], HOME_UNSelectedICONS[i]));
        }

        mTabLayout.setTabData(mTabEntities);
        mTabLayout.setOnTabSelectListener(this);

        fragments = new BaseFragment[HOME_TABS.length];
        ShouYeFragment homeFragment = findFragment(ShouYeFragment.class);
        if (homeFragment == null) {
            homeFragment = ShouYeFragment.newInstance(ShouYeFragment.class.getName());
            DingDanLieBiaoFragment dingDanLieBiaoFragment = DingDanLieBiaoFragment.newInstance(DingDanLieBiaoFragment.class.getName());
            GeRenZhongXinFragment geRenZhongXinFragment = GeRenZhongXinFragment.newInstance(GeRenZhongXinFragment.class.getName());
            fragments[0] = homeFragment;
            fragments[1] = dingDanLieBiaoFragment;
            fragments[2] = geRenZhongXinFragment;
            loadMultipleRootFragment(R.id.home_tab, 0, fragments);
        } else {

            // homeFragment = ShouYeFragment.newInstance(ShouYeFragment.class.getName());
            DingDanLieBiaoFragment dingDanLieBiaoFragment = findFragment(DingDanLieBiaoFragment.class);
            if (dingDanLieBiaoFragment == null) {
                dingDanLieBiaoFragment = DingDanLieBiaoFragment.newInstance(DingDanLieBiaoFragment.class.getName());
            }
            GeRenZhongXinFragment geRenZhongXinFragment = findFragment(GeRenZhongXinFragment.class);
            if (geRenZhongXinFragment == null) {
                geRenZhongXinFragment = GeRenZhongXinFragment.newInstance(GeRenZhongXinFragment.class.getName());
            }
            fragments[0] = homeFragment;
            fragments[1] = dingDanLieBiaoFragment;
            fragments[2] = geRenZhongXinFragment;
        }
        currentFragment = fragments[0];
    }

    boolean isExit;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mTabLayout.getCurrentTab() != 0 && currentFragment != null) {
                mTabLayout.setCurrentTab(0);
                onTabSelect(0);
            } else {
                if (mTabLayout.getCurrentTab() != 0) {
                    mTabLayout.setCurrentTab(0);
                    onTabSelect(0);
                } else {
                    exit();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {

        System.out.println("]	结果:" + (3 == 1 ? "da" : "xiao"));

        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            //mRequestMap.remove(HomeActivity.class.getName());
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            finish();
            System.exit(0);

        }
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }

    };

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void onTabSelect(int position) {
        showHideFragment(fragments[position], currentFragment);
        currentFragment = fragments[position];
    }

    @Override
    public void onTabReselect(int position) {

    }

    public class TabEntity implements CustomTabEntity {
        public String title;
        public int selectedIcon;
        public int unSelectedIcon;

        public TabEntity(String title, int selectedIcon, int unSelectedIcon) {
            this.title = title;
            this.selectedIcon = selectedIcon;
            this.unSelectedIcon = unSelectedIcon;
        }

        @Override
        public String getTabTitle() {
            return title;
        }

        @Override
        public int getTabSelectedIcon() {
            return selectedIcon;
        }

        @Override
        public int getTabUnselectedIcon() {
            return unSelectedIcon;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        currentFragment.onActivityResult(requestCode, resultCode, data);
    }

    private AtomicBoolean isShowForceExitDialog = new AtomicBoolean();

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void forceExit(FroceLogOutMessage froceLogOutMessage) {
        if (isShowForceExitDialog.compareAndSet(true, false)) {
            RefreshToken.getInstance().clearToken();
            showErrorDialog("提示", "您的身份信息已过期，请重新登录", new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    MyActivityManager.finishAll();
                    startActivity(new Intent(MainActivity.this, DengLuActivity.class));
                    MainActivity.this.finish();
                }
            });
        }
    }
}
